// import packages
import * as echarts from 'echarts';
import store from '@/store/index.js';
import { TOKEN_KEY, MILLISECONDS_IN_WEEK, MILLISECONDS_IN_MONTH, MILLISECONDS_IN_THREE_MONTHS } from './constants.js';

/* --------------------------------------------------------------
 *                      Date Picker Options
 * -------------------------------------------------------------- */

/**
 * Configuration object for the date picker shortcuts.
 * @type {Object}
 */
const pickerOptions = {
    /**
     * List of shortcut options available in the picker.
     * @type {Array}
     */
    shortcuts: [
        {
            text: "最近一周",
            onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - MILLISECONDS_IN_WEEK);
                picker.$emit("pick", [start, end]);
            },
        },
        {
            text: "最近一个月",
            onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - MILLISECONDS_IN_MONTH);
                picker.$emit("pick", [start, end]);
            },
        },
        {
            text: "最近三个月",
            onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - MILLISECONDS_IN_THREE_MONTHS);
                picker.$emit("pick", [start, end]);
            },
        },
    ],
};

/* --------------------------------------------------------------
 *                       Statistics Chart
 * -------------------------------------------------------------- */

/**
 * 生成图表配置项
 * @param {Array} dates - 日期数据
 * @param {Array} subscribes - 预约数数据
 * @returns {Object} - 图表的配置项
 */
function generateChartOptions(dates, subscribes) {
    return {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
            },
        },
        xAxis: {
            data: dates,
            name: '日期',
            nameGap: 30,
            axisLabel: {
                rotate: 45,
                fontSize: 12,
            },
        },
        yAxis: {
            name: '预约数',
            nameGap: 40,
        },
        series: [
            {
                name: '预约数',
                type: 'bar',
                data: subscribes,
                color: '#409EFF',
                barWidth: '40%',
            },
        ],
    };
}

/**
 * 渲染图表
 * @param {string} chartId - 图表容器的 DOM 元素 ID
 * @param {Object} chartData - 需要显示的数据
 * @returns {void}
 */
function renderChart(chartId, chartData) {
    const dates = Object.keys(chartData)
        .filter((key) => key.startsWith('date'))
        .map((key) => chartData[key]);

    const subscribes = Object.keys(chartData)
        .filter((key) => key.startsWith('subscribe'))
        .map((key) => chartData[key]);

    // 初始化图表
    const chart = echarts.init(document.getElementById(chartId));

    // 获取图表配置项
    const option = generateChartOptions(dates, subscribes);

    // 设置图表
    chart.setOption(option);
}

/* --------------------------------------------------------------
 *                            Token
 * -------------------------------------------------------------- */

/**
 * Store token in local storage
 * @param {Object} token
 * @returns {void}
 */
function setUserToken(token) {
    localStorage.setItem(TOKEN_KEY, token);
}

/**
 * Get token from local storage
 * @returns {Object}
 */
function getUserToken() {
    return store.state.user.token || localStorage.getItem(TOKEN_KEY) || "";
}

/**
 * Remove token from local storage
 * @returns {void}
 */
function removeUserToken() {
    localStorage.removeItem(TOKEN_KEY);
}

/* --------------------------------------------------------------
 *                       Common Functions
 * -------------------------------------------------------------- */
/**
 * Formats date to YYYY-MM-DD
 * @param {Date} date
 * @returns {String}
 */
function formateDate(date) {
    const formattedDate = new Intl.DateTimeFormat('zh-CN').format(date);
    return formattedDate.replace(/\//g, '-');
}

/**
 * Generate a random Chinese character
 * @returns {string}
 */
function getRandomChineseChar() {
    const min = 0x4E00;
    const max = 0x7FA5;

    const codePoint = Math.floor(Math.random() * (max - min + 1)) + min;
    return String.fromCodePoint(codePoint);
}

/**
 * Generate random Chinese characters
 * @param {Number} num 
 * @returns {string}
 */
function getRandomChineseChars(num = 1) {
    let chars = "";
    for (let i = 0; i < num; i++) {
        const char = getRandomChineseChar();
        chars = chars.concat(char);
    }
    return chars;
}

/**
 * Generate a random number between min and max
 * @param {Number} min
 * @param {Number} max
 */
function getRandomNum(min = 0, max = 9) {
    return Math.floor(Math.random() * max) + min;
}

/**
 * Generate random numbers
 * @param {number} num 
 * @returns {string}
 */
function getRandomNumbers(num = 1) {
    let numbers = "";
    for (let i = 0; i < num; i++) {
        const number = getRandomNum();
        numbers = numbers.concat(number);
    }
    return numbers;
}

/**
 * Get random number between start and end
 * @param {String} start 
 * @param {String} end 
 */
function getRandomDate(start = "2000-01-01", end = "2025-01-01") {
    const startDate = new Date(start).getTime();
    const endDate = new Date(end).getTime();
    return new Date(startDate + Math.random() * (endDate - startDate));
}

/**
 * Generate random appointment records
 * @returns {Array}
 */
function randomAppointment() {
    const createTime = getRandomDate();
    const updateTime = getRandomDate(createTime)
    return {
        id: getRandomNumbers(11),
        userName: getRandomChineseChars(3),
        status: getRandomNum(0, 1),
        createTime,
        updateTime,
        appointmentTime: getRandomDate(createTime),
        appointmentContent: getRandomChineseChars(30),
        userId: getRandomNumbers(11),
        userTel: getRandomNumbers(11),
        userSfz: getRandomNumbers(18),
        userUnite: getRandomChineseChars(5),
        professorId: getRandomNumbers(11),
        professorName: getRandomChineseChars(3),
        isDel: getRandomNum(0, 1),
        type: "审核中"
    }
}

/**
 * Generate random appointments
 * @param {Number} num - The number of appointments to generate
 * @returns {Array}
 */
function randomAppointments(num) {
    const appointments = [];
    for (let i = 0; i < num; i++) {
        appointments.push(randomAppointment());
    }
    return appointments;
}

export { pickerOptions, formateDate, renderChart, setUserToken, getUserToken, removeUserToken, randomAppointments };